// 湍口镇 这个菜单前面要加空格，不然label的文字 都掉出地图外面了~~~~记得啊 这个很重要
var mapSchemaCharts = echarts.init(document.getElementById('middleMap'));
//this.mapSchemaCharts = mapSchemaCharts;
mapSchemaCharts.showLoading(
  {
    text: '正在加载...',
    color: '#fff',
    textColor: '#fff',
    maskColor: 'rgba(0,0,0,0)'
  }
);
echarts.registerMap('linan', linan)
echarts.registerMap('jingcheng', jingcheng)

let optionLinan;
let getOptionStreet = function (streetName, paramArr) {
  return {
    tooltip: {
      show : true,
      backgroundColor: 'rgba(255,255,255,0.9)',
      borderWidth:0,
      textStyle: {
        color: '#000',
        lineHeight: '24px',
      },
      extraCssText: 'border-radius:10px',
      borderRadius: '10px',
      padding: [15, 50, 15, 20],
      trigger: 'item',
      formatter: (params) => {
        if( params.componentSubType == "map" ) {
          let h1 =
            `<div style="font-size:18px;font-weight:600;margin-bottom:10px;color:#000">${streetName}</div>`;
          let obj = middlleMapData[streetName] || {};
          h1 +=  `<div style="font-size: 14px;line-height: 18px;"> 安置房（限价房）总量：${obj.azHouseCount || 0 }套</div>`
          h1 +=  `<div style="font-size: 14px;line-height: 18px;"> 公（廉）租房总量：${obj.gzHouseCount || 0 }套</div>`
          h1 +=  `<div style="font-size: 14px;line-height: 18px;"> 人才房总量：${obj.rcHouseCount || 0 }套</div>`
          h1 +=  `<div style="font-size: 14px;line-height: 18px;"> 保障性租赁住房总量：${obj.bzHouseCount || 0 }套</div>`
          return h1
        } else if ( params.componentSubType == "custom" ) {
          let obj = params.data;
          let h1 =
            `<div style="font-size:14px;font-weight:600;margin-bottom:10px;color:#000">${obj.communityName}</div>`;
          h1 +=  `<div style="font-size: 14px;line-height: 18px;"> 安置房（限价房）总量：${obj.azHouseCount || 0 }套</div>`
          h1 +=  `<div style="font-size: 14px;line-height: 18px;"> 公（廉）租房总量：${obj.gzHouseCount || 0 }套</div>`
          h1 +=  `<div style="font-size: 14px;line-height: 18px;"> 人才房总量：${obj.rcHouseCount || 0 }套</div>`
          h1 +=  `<div style="font-size: 14px;line-height: 18px;"> 保障性租赁住房总量：${obj.bzHouseCount || 0 }套</div>`
          return h1;
        }
      }
    },
    series: [{
      type: 'map',
      mapType: streetName,//这个地方是重点,
      roam: false,
      zoom: middlleMapData[streetName].zoom,
      scaleLimit: {
        min: 1,
        max: 20,
      }, top: 20,
        selectedMode: false,
      layoutSize: 500,//省份地图大小为600xp。
      layoutCenter: ['50%', '50%'],//距左百分比，距上百分比
      itemStyle: {
        normal: {
          areaColor: '#0033e8',
          borderColor: '#2558a5',
          borderWidth: 1,
          color: "#FFFFFF",
          areaOpacity: 1,
          label: {show: true, color: 'white', fontSize: 14}
        },
        emphasis: {areaColor: '#7916ff', label: {show: true, color: 'white'},}
      },
      data: lineData
    }, {
      name: '图标',
      type: 'custom',
      roam: false,
      zlevel: 30,
      coordinateSystem: 'geo',
      renderItem: function (params, api) {//具体实现自定义图标的方法
       var seriesModel = mapSchemaCharts.getModel().getSeriesByIndex(0);
        var coordSys = seriesModel.coordinateSystem;
        var point = coordSys.dataToPoint([parseFloat(paramArr[params.dataIndex].longitude), parseFloat(paramArr[params.dataIndex].latitude)]) || [0, 0];
        return {
          type: 'image',
          style: {
            image: '',
            x: point[0]+10,
            y: point[1]-4,
            width: 8,
            height: 8
          }
        }
      },
      data: paramArr
    }]
  }
}

var isProvince = true;  // 是否有返回

let middlleMapData = {
  锦城街道: {
    zoom: 1.2,
    houseTotalCount: 54
  },
  玲珑街道: {
    zoom: 0.8,
    houseTotalCount: 34
  },
  青山湖街道: {
    zoom: 0.8,
    houseTotalCount: 3
  },
  锦南街道: {
    zoom: 0.8,
    houseTotalCount: 19
  },
  锦北街道: {
    zoom: 1.2,
    houseTotalCount: 5
  },
  板桥镇: {
    zoom: 0.8,
    houseTotalCount: 12
  },
  高虹镇: {
    zoom: 0.8,
    houseTotalCount: 45
  },
  太湖源镇: {
    zoom: 0.8,
    houseTotalCount: 2
  },
  於潜镇: {
    zoom: 0.8,
    houseTotalCount: 23
  },
  天目山镇: {
    zoom: 0.8,
    houseTotalCount: 18
  },
  太阳镇: {
    zoom: 0.8,
    houseTotalCount: 40
  },
  潜川镇: {
    total: 11,
    zoom: 0.8,
    houseTotalCount: 7
  },
  昌化镇: {
    zoom: 0.8,
    houseTotalCount: 12
  },
  龙岗镇: {
    zoom: 0.8,
    houseTotalCount: 45
  },
  河桥镇: {
    zoom: 1.5,
    houseTotalCount: 4
  },
  ' 湍口镇': {
    zoom: 0.8,
    houseTotalCount: 7
  },
  清凉峰镇: {
    zoom: 0.8,
    houseTotalCount: 33
  },
  岛石镇: {
    zoom: 0.8,
    houseTotalCount: 54
  },
}

var linanStreet = ['玲珑街道', '锦南街道', '锦城街道', '锦北街道', '青山湖街道', '高虹镇', '太湖源镇', '於潜镇', '太阳镇', '潜川镇', '昌化镇', '河桥镇', ' 湍口镇', '清凉峰镇', '岛石镇', '板桥镇', '天目山镇', '龙岗镇'];
var lineData = [];
var maxLineValue = 0;
var dataArr = [];
var dotArr = []; // 小区打点
for (let i = 0; i < linanStreet.length; i++) {
  if (linanStreet[i] !== '锦城街道') { // 锦城街道有2块区域 十分特殊
    echarts.registerMap(linanStreet[i], {
        "type": "FeatureCollection",
        "features": [linan.features[i]]
      }
    )
  } else {
    echarts.registerMap(linanStreet[i], jingcheng);
  }
}

let renderMap = () => {
  isProvince = true
  mapSchemaCharts.clear();
  optionLinan = {
    tooltip: {
      show : true,
      backgroundColor: 'rgba(255,255,255,0.9)',
      borderWidth:0,
      textStyle: {
        color: '#000',
        lineHeight: '24px',
      },
      extraCssText: 'border-radius:10px',
      borderRadius: '10px',
      padding: [15, 50, 15, 20],
      trigger: 'item',
      formatter: (params) => {
        if( params.componentSubType == "map" ) {
          let h1 =
            `<div style="font-size:18px;font-weight:600;margin-bottom:10px;color:#000">${params.name}</div>`;
          let obj = middlleMapData[params.name] || {};
          h1 +=  `<div style="font-size: 14px;line-height: 18px;"> 安置房（限价房）总量：${obj.azHouseCount || 0 }套</div>`
          h1 +=  `<div style="font-size: 14px;line-height: 18px;"> 公（廉）租房总量：${obj.gzHouseCount || 0 }套</div>`
          h1 +=  `<div style="font-size: 14px;line-height: 18px;"> 人才房总量：${obj.rcHouseCount || 0 }套</div>`
          h1 +=  `<div style="font-size: 14px;line-height: 18px;"> 保障性租赁住房总量：${obj.bzHouseCount || 0 }套</div>`
          return h1;
        } else if ( params.componentSubType == "custom" ) {
          let obj = params.data;
          let h1 =
            `<div style="font-size:14px;font-weight:600;margin-bottom:10px;color:#000">${obj.communityName}</div>`;
          h1 +=  `<div style="font-size: 14px;line-height: 18px;"> 安置房（限价房）总量：${obj.azHouseCount || 0 }套</div>`
          h1 +=  `<div style="font-size: 14px;line-height: 18px;"> 公（廉）租房总量：${obj.gzHouseCount || 0 }套</div>`
          h1 +=  `<div style="font-size: 14px;line-height: 18px;"> 人才房总量：${obj.rcHouseCount || 0 }套</div>`
          h1 +=  `<div style="font-size: 14px;line-height: 18px;"> 保障性租赁住房总量：${obj.bzHouseCount || 0 }套</div>`
          return h1;
        }
      }
    },
    visualMap: {
      type: 'piecewise',
      itemSymbol:'circle',
      itemGap:12,
      min: 0,
      max: 1000,
      right: 0,
      bottom: -0,
      textStyle: {
        color: '#ffffff'
      },
      inverse:true,
      calculable: true,
      align:'left',
      pieces: [{
        gte: 0,
        lt:200,
        label: "0-200间",
        color: "#0256FF"
      },{
        gte:200,
        lte: 500,
        label: "200-500间",
        color: "#022FC7"
      }, {
        gt: 500,
        lte: 1000,
        label: "500-1000间",
        color: "#00128B"
      }, {
        gt: 1000,
        label: "1000间以上",
        color: "#29117D"
      }],
      show: !0
    },
    roam:true,
    series: [{
      type: 'map',
      mapType: 'linan',//这个地方是重点,
      roam: true,
      zoom:1,
      scaleLimit: {
        min: 1,
        max: 20,
      }, top: 20,
        layoutSize: 700,
      layoutCenter: ['50%', '50%'],//距左百分比，距上百分比
      itemStyle: {
        normal: {
          areaColor: '#0033e8',
          borderColor: '#a2a7e3',
          borderWidth: 1,
          color: "#ffffff",
          areaOpacity: 1,
          label: {show: true, color: 'white', fontSize: 14}
        },
        emphasis: {areaColor: '#7916ff', label: {show: true, color: 'white'},}
      },
      data:lineData,
      label: {
        normal: {
          textStyle: {
            fontSize: 12,
            fontWeight: 'bold',
            color: '#fff'
          }
        }
      }
    }, {
      name: '图标',
      type: 'custom',
      zlevel: 100,
      coordinateSystem: 'geo',
      label: {
        normal: {
          formatter: "{b}",
          position: "right",
          show: true
        }
      },
      renderItem: function (params, api) {//具体实现自定义图标的方法
        var seriesModel = mapSchemaCharts.getModel().getSeriesByIndex(0);
        var coordSys = seriesModel.coordinateSystem;
        var point = coordSys.dataToPoint([parseFloat(dataArr[params.dataIndex].longitude), parseFloat(dataArr[params.dataIndex].latitude)]) || [0, 0];

        return {
          type: 'image',
          style: {
            image: '',
            x:point[0]+10,
            y: point[1]-4,
            width: 8,
            height: 8
          }
        }
      },
      data: dataArr
    }],
  };
  mapSchemaCharts.setOption(optionLinan, true);
  mapSchemaCharts.off('click').on('click', function (params) {
    $('.middle-label-bg').hide();
    if(params.componentSubType === "map") {
      if (isProvince) {
        isProvince = false;
        $('#middleBack').show();
        var jiedao = params.name;
        mapSchemaCharts.clear();
        mapSchemaCharts.off('click')
        dotArr = [];
        // 其中端口镇 前面加了空格
        ajaxCall("/getCommunityCoordinate?area=" + jiedao.replace(' ','') ).then((ret)=>{
          dotArr = ret.data;
          mapSchemaCharts.setOption(getOptionStreet(jiedao,dotArr))
        })

      }
    }
  });
  mapSchemaCharts.hideLoading();
  $('.middle-label-bg').show();
};

let getMap = async () => {
  lineData = [];
  let ret = await ajaxCall("/getStreetInfo", {})
  let retData = ret.data
  for(let i=0;i<retData.length;i++) {

    if(retData[i].streetName){
      if(retData[i].streetName=='湍口镇') retData[i].streetName = ' 湍口镇';
      let total = 0;
      total = (~~retData[i].azHouseCount) + (~~retData[i].gzHouseCount) + (~~retData[i].rcHouseCount) + (~~retData[i].bzHouseCount)
      middlleMapData[retData[i].streetName] = { ...retData[i], ...middlleMapData[retData[i].streetName],total:total};
    }
  }
  for(let i=0;i<linanStreet.length;i++){
    lineData.push({name: linanStreet[i], value: middlleMapData[linanStreet[i]].total || 0 })
  }
  let res = await ajaxCall("/getCommunityCoordinate")
  dataArr = res.data;
  renderMap();
}


$(function () {
  getMap();

  $('#middleBack').on('click',function () {
    $(this).hide();
    renderMap();
  })
})


/*
*
*     let obj = middlleMapData[key];
        let ret = await ajaxCall("/getCityMapData/" + key, {});
        let temp = `<li style="left:${obj.left}px;top:${obj.top}px;"><span>${key}</span><div class="map-tips map-tips1" style="width:300px;"><h3>${key}</h3>
		              <p>${ret.data.houseTotalCount || 0} 套</p>
					  <p>分布小区数量：${ret.data.communityTotalCount || 0} 个</p>
		            </div>
		          </li>`
        string += temp;
*
* */